package com.vineetmanohar.nitrogen.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.google.common.io.Files;
import com.vineetmanohar.nitrogen.CodeGenerator;

public class SingleFileFormatter {
	public static void main(String[] args) throws IOException {
		File myTempDir = Files.createTempDir();
		File templateBaseDir = new File(myTempDir, "template");
		templateBaseDir.mkdir();

		File modelFile = new File(myTempDir, "model.xml");
		FileOutputStream modelOutputStream = new FileOutputStream(modelFile);

		boolean debugging = false;
		if (debugging) {
			FileUtils.copyFile(new File("src/test/data/model2.xml"), modelFile);
		} else {
			IOUtils.copy(System.in, modelOutputStream);
		}

		File outputBaseDir = new File(myTempDir, "output");
		outputBaseDir.mkdir();

		String templateFilePath;

		if (debugging) {
			templateFilePath = "src/test/data/input2.txt";
		} else {
			templateFilePath = args[0];
		}

		File originalTemplateFile = new File(templateFilePath);
		File templateFile = new File(templateBaseDir,
				originalTemplateFile.getName());
		FileUtils.copyFile(originalTemplateFile, templateFile, true);
		CodeGenerator.generate(modelFile, templateBaseDir, outputBaseDir);

		System.out.println("Output generated in: "
				+ outputBaseDir.getAbsolutePath());

		// print the output to stdout
		IOUtils.copy(
				new FileReader(new File(outputBaseDir, templateFile.getName())),
				System.out);
	}
}